package keter.framework.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import keter.framework.model.Codelist;
import keter.framework.model.base.BaseModel;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Model;

public class ModelUtil {
    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(ModelUtil.class);

    public static String toJson(Object model) {
        return JsonKit.toJson(model);
    }

    public static Map getMap(String jsonStr) {
        // return new ObjectMapper().readValue(jsonStr, HashMap.class);
        return JSONObject.parseObject(jsonStr, HashMap.class);
    }

    public static <T> List<T> getArray(String jsonStr, Class<T> clazz) {
        // return new ObjectMapper().readValue(jsonStr, HashMap.class);
        return JSONObject.parseArray(jsonStr, clazz);
    }

    /**
     * 接受application/json请求并转换成JsonModel
     * 
     * @param request
     * @return
     * @author gulixing@msn.com
     * @date 2015年11月27日
     */
    public static BaseModel toModel(HttpServletRequest request, BaseModel model) {
        StringBuffer json = new StringBuffer();
        String line = null;
        BufferedReader reader;
        try {
            reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                json.append(line);
            }
        } catch (IOException e) {
            logger.error("json解析失败", e);
        }

        return toModel(json.toString(),model);
    }
   
    
    public static BaseModel toModel(String json, BaseModel model) {
        Map<String, Object> map = Maps.newHashMap();
        try {
            map = json2Map(json.toString());
        } catch (UnsupportedEncodingException e) {
            logger.error("json转换异常", e);
        }
        return (BaseModel) model.put(map);
    }

    private static Map<String, Object> json2Map(String json) throws UnsupportedEncodingException {
        json = URLDecoder.decode(json, "utf-8");
        return (Map<String, Object>) JSON.parse(json);
    }
    
    
	/**
	 * 按照某个属性将model集合中的内容提取成"sql in"查询条件串，
	 * 即:提取[{x:a},{x:b}]为【'a','b'】的形式
	 * @param collection
	 * @param propertyName
	 * @param separator
	 * @return 
	 * @author  gulixing@msn.com
	 * @date    2015年12月5日
	 */
	public static String extractListToSqlIn(final List collection, final String propertyName) {
		List list = extractToSqlInList(collection, propertyName);
		return StringUtils.join(list, ",");
	}
	
	/**
	 * @param collection
	 * @param propertyName
	 * @return 
	 * @author  gulixing@msn.com
	 * @date    2015年12月5日
	 */
	private static List extractToSqlInList(final List collection, final String propertyName) {
		List list = new ArrayList(collection.size());
			for (Object obj : collection) {
				list.add("'"+((Model) obj).get(propertyName)+"'");
			}
		return list;
	}
	
    
    public static void main(String[] args) throws UnsupportedEncodingException {
        String json ="{\"username\":\"abc\",\"password\":\"haha\"}";
        Map map = ModelUtil.json2Map(json);
        System.out.println(map);
        Codelist c = new Codelist();
    }
}